package com.wgworkshop.pems.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * AccessToken验证拦截器。
 * Created by lcwang on 2018/3/23.
 */
@Component
public class AccessTokenVerifyInterceptor extends HandlerInterceptorAdapter {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.audience}")
    private String audience;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        int result = 0;
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authHeader)) {
            // 请求中没有认证信息
            result = -1;
        } else if (!authHeader.startsWith("Bearer ")) {
            // 请求中认证信息格式不正确
            result = -2;
        } else {
            String token = authHeader.substring(7);
            if (StringUtils.isEmpty(token)) {
                // 用户Token为空
                result = -3;
            } else {
                try {
                    Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
                    String aud = claims.getAudience();
                    if (!audience.equals(aud)) {
                        // 用户Token中接收方错误
                        result = -6;
                    }
                } catch (ExpiredJwtException e) {
                    // 用户Token过期
                    e.printStackTrace();
                    result = -5;
                } catch (Exception e) {
                    // 用户Token格式不正确
                    e.printStackTrace();
                    result = -4;
                }
            }
        }

        String message = "";
        switch (result) {
            case -1:
                message = "请求中没有认证信息，拒绝访问。";
                break;
            case -2:
                message = "请求中认证信息格式不正确，拒绝访问。";
                break;
            case -3:
                message = "用户Token为空，拒绝访问。";
                break;
            case -4:
                message = "用户Token格式不正确，拒绝访问。";
                break;
            case -5:
                message = "用户Token过期，请重新登录。";
                break;
            case -6:
                message = "用户Token中接收方错误，请联系系统管理员。";
                break;
        }

        if (result < 0) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.setCharacterEncoding("UTF-8");

            response.getWriter().print(message);
        }

        return result == 0;
    }
}
